<template>
  <div class="title">
    <div class="returns" @click="toReleaseInformation">
      <!-- <img src="@/assets/images/icon_back_arrow.png" alt="" /> -->
      <svg-icon class="icon-back-arrow" name="icon_back_arrow" :width="20" :height="20" />
      返回
    </div>
    <div v-if="route.query.state !== '草稿箱修改'" class="step">
      <div
        class="first"
        :class="stepValue * 1 === 1 ? 'step-active' : 'step-right'"
        @click="stepValue * 1 === 2 ? toReleaseInformation(2) : null"
      >
        <div class="yuan">1</div>
        <div class="step-name">{{ setUpList[0] }}</div>
      </div>
      <div
        class="first"
        :class="stepValue * 1 === 2 ? 'step-active' : 'step-left'"
        @click="onPublic('to')"
      >
        <div class="yuan">2</div>
        <div class="step-name">{{ setUpList[1] }}</div>
      </div>
    </div>
    <div>
      <div v-if="route.query.state === 'device'" class="next-button">
        <a-button class="save wsave mg-l8" @click="toReleaseInformation(2)">上一步</a-button>
        <a-button class="save wsave" @click="onPublic(3)">保存为草稿</a-button>
        <a-button v-if="positionTypes !== 2" class="save marg-left16" @click="onPublic(2)"
          >定时发布</a-button
        >
        <a-button class="next marg-left16" @click="onPublic(1)"> 发布 </a-button>
      </div>
      <div v-else class="next-button">
        <a-button class="save wsave" @click="onPublic(0)">保存为草稿</a-button>
        <a-button
          v-if="route.query.state !== '草稿箱修改'"
          class="next marg-left16"
          @click="onPublic('to')"
        >
          下一步
        </a-button>
      </div>
    </div>
  </div>

  <!-- 上传图像 -->
  <Form class="form" name="basic" autocomplete="off">
    <Form.Item label="上传图像" name="upload" :rules="[{ required: true, validator: checkPic }]">
      <div class="all-upload">
        <Upload
          v-model:file-list="coverFileList"
          class="upfileBox"
          list-type="picture"
          accept=".png, .jpeg, .jpg, .mp4"
          :multiple="true"
          :custom-request="handleChange"
        >
          <!-- 现在大小{{ allSizeNum }}；总大小： 5368709120 -->
          <div v-if="allSizeNum / 1024 / 1024 / 1024 < 5" class="upload">
            <div class="upload-content">
              <img class="upload-icon" src="../../../src/assets/icons/images/upload.png" />
              <div class="ant-upload-text"></div>
              <div class="tip"> 支持格式MP4、JPG、JPEG、PNG </div>
              <div class="tip"> 总体大小≤5G</div>
            </div>
          </div>
        </Upload>
        <Draggable
          v-model:value="modelList"
          :list="pictureLists"
          :animation="100"
          item-key="id"
          class="upload-listes"
          :force-fallback="true"
          ghost-class="ghost"
          filter=".unmover"
        >
          <template #item="{ element, index }">
            <div
              :class="
                element.exception !== 'exceptionSuccess'
                  ? 'img-list uploadings'
                  : 'uploads img-list'
              "
            >
              <!--  新上传的 展示进度 等 -->
              <div v-if="element.progressValue * 1 !== 100" class="upload-ings">
                <div class="upload-img">
                  <!-- 上传中展示 -->
                  <tj-loading
                    v-if="element.exception === 'exceptionLoading'"
                    size="small"
                    text=""
                  ></tj-loading>
                </div>
                <div class="upload-tips">
                  <div v-if="element.exception === 'exceptionLoading'">
                    上传中{{ element.progressValue }}%
                  </div>
                  <div v-if="element.exception === 'retry'">
                    <img src="../../assets/images/icon_chuanshushibai@2x.png" class="err-tips" />
                    上传失败
                  </div>
                </div>
              </div>
              <!-- 上传失败展示 -->
              <div
                v-if="element.exception === 'retry' && element.progressValue !== 100"
                class="err-bgss"
              >
                <div class="err-delete-img">
                  <div class="err-looks">
                    <img
                      src="../../assets/images/aa.png"
                      style="margin-right: 38px"
                      @click="deleteImg(index)"
                    />
                    <img
                      src="../../assets/images/chongxinshangchuan@2x.png"
                      @click="getAgainFile(element.urlTime, index)"
                    />
                  </div>
                </div>
              </div>
              <!-- 上传成功展示封面 img video -->
              <img
                v-if="element.customType === 'img' && element.progressValue === 100"
                class="upload-icon img-width"
                :src="element.url"
              />
              <video
                v-if="element.customType === 'video' && element.progressValue === 100"
                :id="index"
                class="upload-icon img-width"
                :src="element.url"
                crossorigin="anonymous"
              ></video>
              <div class="bgss">
                <div class="delete-img">
                  <div class="looks">
                    <img
                      src="../../assets/images/bb.png"
                      class="unmover look"
                      @click="lookImg(index)" />
                    <img class="unmover" src="../../assets/images/aa.png" @click="deleteImg(index)"
                  /></div>
                </div>
              </div>
            </div>
          </template>
        </Draggable>
      </div>
      <div v-if="pictureLists.length !== 0" class="statistics">
        共计：{{ pictureLists.length }}
        <button class="qingkong" @click="empty">清空</button>
      </div>
    </Form.Item>
    <Form.Item label="发布名称" name="name" :rules="[{ required: true, validator: checkPic }]">
      <a-input
        v-model:value="releaseName"
        placeholder="请输入发布名称"
        class="release-name"
        @change="releaseNameChange(releaseName.replace(/\s+/g, ''))"
      ></a-input>
      <span class="release-name-number">{{ releasenameNumber }}/50</span>
    </Form.Item>
    <Form.Item label="发布描述" name="describe" class="form-describe">
      <a-textarea
        v-model:value="describeName"
        placeholder="请输入发布描述内容"
        class="describe-name"
        @change="describeNameChange(describeName)"
      ></a-textarea>
      <span class="describe-name-number">{{ describenameNumber }}/140</span>
    </Form.Item>
    <template v-if="customType.indexOf('img') !== -1 || customType.length === 0">
      <Form.Item label="展示时长:" name="timeLong" class="form-time">
        <a-input-number
          v-model:value="durationTime"
          :min="1"
          :max="timeButton === '0' ? 86400 : timeButton === '1' ? 1440 : 24"
          :precision="0"
          placeholder="请输入大于0的整数作为展示时长"
          class="time"
        ></a-input-number>
        <a-button v-if="timeButton === '0'" type="primary" @click="timeButton = '0'">秒</a-button>
        <a-button v-else class="color9" @click="timeButton = '0'">秒</a-button>
        <a-button v-if="timeButton === '1'" type="primary" @click="minuteBtn">分</a-button>
        <a-button v-else class="color9" @click="minuteBtn">分</a-button>
        <a-button v-if="timeButton === '2'" type="primary" @click="hourBtn">时</a-button>
        <a-button v-else class="color9" @click="hourBtn">时</a-button>
        <div class="button-tips">
          <div>展示时长为单个素材的停留时间。</div>
          <!-- <div>注：将信息发布到应用平台，如：动态管理等，图片为固定展示，展示时长不生效。</div> -->
        </div>
      </Form.Item>
    </template>
  </Form>
  <!-- 图片视频预览组件 -->
  <image-viewer
    v-model:visible="imgDialog.visible"
    v-model:index="curImgIdx"
    :images="previewImgs"
  />
  <my-dialog
    :dialog-state="deleteDialog.visible"
    :dialog-title="deleteDialog.title"
    :dialog-width="deleteDialog.width"
    :icon-type="deleteDialog.warring"
    :show-icon="true"
    :draft-box-visible="false"
    :content-text="deleteDialog.content"
    @handleCancel="deleteDialogCancel"
    @handleOk="deleteDialogOk"
  ></my-dialog>
  <!-- 发布设置弹窗 -->
  <my-dialog
    :dialog-state="publishDialog.visible"
    :dialog-title="publishDialog.title"
    :dialog-width="publishDialog.width"
    :icon-type="publishDialog.default"
    :but-status="publishDialog.butStatus"
    @handleCancel="publishDialogCancel"
    @handleOk="publishDialogOk"
  >
    <template #location>
      <div class="times">
        <div class="tips">*</div>
        <div>发布时长：</div>
        <a-range-picker
          v-model:value="publishTime"
          format="YYYY-MM-DD HH:mm"
          show-time
          :disabled-date="disabledDate"
          :disabled="[true, permanentChecked ? true : false]"
          :disabled-time="disabledDateTime"
          @ok="ok"
          @openChange="openChange"
          @change="selsectTime"
          @calendarChange="onCalendarChange"
        />
      </div>
      <div v-if="permanentChecked" class="time-slot">永久</div>
      <div v-else class="time-slot">{{ timeFn }}</div>
      <div class="permanent-switch">
        <div class="permanent">永久发布：</div>
        <a-switch v-model:checked="permanentChecked" @change="isForeverChange" />
      </div>
    </template>
  </my-dialog>
  <!-- 定时发布 -->
  <regular-release-dialog
    ref="regularReleaseChild"
    :timing-data="timingData"
    :timing-state="timingState"
    :regular-release="regularRelease.visible"
    @handleCancel="regularReleaseCancel"
    @handleOks="regularReleaseOk"
  ></regular-release-dialog>
  <!-- 发布提示弹窗 -->
  <my-dialog
    :dialog-state="publishTipsDialog.visible"
    :dialog-title="publishTipsDialog.title"
    :dialog-width="publishTipsDialog.width"
    :icon-type="publishTipsDialog.default"
    :but-status="publishTipsDialog.butStatus"
    :btn-title="publishTipsDialog.btnTitle"
    :determine-btn="publishTipsDialog.determineBtn"
    :other-btn="true"
    class="publish-tips-dialog"
    :btn-state="publishTipsDialog.btnState"
    @handleOther="publishTipsDialogOther"
    @handleCancel="publishTipsDialog.visible = false"
    @handleOk="publishTipsDialogOk"
  >
    <template #location>
      <div class="publish-scrollbar">
        <div class="content">
          <div class="content-left">
            <i :class="'icon-warring'" class="icon"></i>
            <span class="text">继续发布将覆盖正在发布信息的部分时段</span>
          </div>
          <div class="tipss"> （设备在所选时间内正在展示以下信息） </div>
        </div>
        <div class="off-line-equipment-list">
          <a-table :data-source="conflictDevice" :columns="columns">
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'equipmentName'">
                {{ record.equipmentName }}
              </template>
              <template v-else-if="column.dataIndex === 'model'">
                <div v-if="record.conflict === 0" class="equipment-choices">霸屏模式</div>
                <div v-else class="equipment-choicess">全屏模式</div>
              </template>
              <template v-else-if="column.dataIndex === 'releaseUserName'">
                {{ record.releaseUserName ? record.releaseUserName : '--' }}
              </template>
              <template v-else-if="column.dataIndex === 'releaseName'">
                {{ record.releaseName }}
              </template>
              <template v-else>
                <div class="equipment-choice" @click="choiceEquipment(index, record.equipmentId)"
                  >取消选择</div
                >
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </template>
  </my-dialog>
  <div v-if="loading" class="loading">
    <Spin class="" tip="加载中..."></Spin>
  </div>
  <my-dialog
    :dialog-state="leaveDialog.visible"
    :dialog-title="leaveDialog.title"
    :dialog-width="leaveDialog.width"
    :icon-type="leaveDialog.warring"
    :determine-btn="true"
    :btn-title="leaveDialog.otherBtn"
    :btn-state="leaveDialog.determineBtn"
    :other-btn="true"
    :html="leaveDialog.html"
    :show-icon="true"
    :footer="true"
    :content-text="leaveDialog.content"
    @handleCancel="leaveDialog.visible = false"
    @handleOther="leaveDialogCancel"
    @handleOk="leaveDialogOk"
  ></my-dialog>
</template>
<script>
export default {
  name: 'imgAndVideo'
};
</script>
<script setup>
import ObsClient from 'esdk-obs-browserjs';
import MyDialog from '@/components/dialog/index.vue';
import Draggable from 'vuedraggable';
import store from '../../store';
import {
  deleteOBS,
  uploadOBS,
  deleteAllOBS,
  timeFns,
  getEscapeUrl,
  getSum,
  arrayUnique,
  columns
} from '../../util/OBSUpload';
import { Upload, Form, Message, Progress, Popover, Spin } from 'ant-design-vue';
import { LockFilled, PlusOutlined } from '@ant-design/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import ImageViewer from '@/components/imageViewer';
import {
  saveInfoImageDraft,
  saveInfoImage,
  getInfoImage,
  checkCollide,
  getAccessGet
} from '@/api/user';
import moment from 'moment';
import { ref, watch, onMounted, reactive, defineEmits, defineExpose } from 'vue';
import regularReleaseDialog from '@/components/regularReleaseDialog/index.vue'; // 定时发布弹窗
import dayjs, { Dayjs } from 'dayjs';
import { format } from 'echarts';
import { nextTick } from 'process';
import { getFromRouteInfo } from '@/util/utils';

// 弹窗相关
const leaveDialog = reactive({
  type: '',
  title: '温馨提示',
  html: 'html',
  content:
    '<div>有编辑的内容未发布，是否确认返回？</br>返回后将不会保存编辑内容，您可以先保存到草稿</div>',
  warring: 'warring',
  visible: false,
  otherBtn: '确认返回',
  determineBtn: '保存草稿后返回',
  width: '464px'
});
let curImgIdx = ref(0);
let previewImgs = ref([]);
// 返回
function toReleaseInformation(params) {
  // console.log(route.query);
  // console.log(3333, route);
  // console.log('返回', goBackState.value);
  if (Object.keys(route.query).length === 0) {
    console.log(11111);
    didagState();
  } else if (
    route.query.type === 'creatDraft' ||
    route.query.state === '编辑' ||
    route.query.state === '草稿箱修改' ||
    route.query.isBack === 'true'
  ) {
    console.log(222222);
    didagState();
  } else {
    // 区分本地和基座内部，封装返回上一页方法
    if (window.__MICRO_APP_ENVIRONMENT__) {
      router.push(getFromRouteInfo());
    } else {
      router.go(-1);
    }
    store.commit('addCacheRoute', 'postMessage');
    store.commit('addCacheRoute', 'imgAndVideo');
  }
}
function leaveDialogCancel() {
  leaveDialog.visible = false;
  store.commit('removeCacheRoute', 'postion');
  store.commit('removeCacheRoute', 'postMessage');
  store.commit('removeCacheRoute', 'imgAndVideo');
  router.push({
    path: '/service/send'
  });
}
function didagState() {
  if (goBackState.value.length > 0) {
    console.log('打开弹窗');
    leaveDialog.visible = true;
  } else {
    store.commit('removeCacheRoute', 'postMessage');
    store.commit('removeCacheRoute', 'postion');
    console.log('不打开');
    router.push({
      path: '/service/send'
    });
  }
}
defineExpose({ getSaveDraft });
function getSaveDraft() {
  console.log('dsjgksdfj ');
  onPublic(0);
}
function leaveDialogOk() {
  leaveDialog.visible = false;
  onPublic(0);
}
// 必选项
const checkPic = (rule, value) => {};
const router = useRouter();
const route = useRoute();
const modelList = ref([]);
let Base64 = require('js-base64').Base64;
let pictureLists = ref([]);
let positionTypes = ref(); // 应用平台 ==2
let videoType = ref('mp4'); // 视频类型
let videoSize = ref(''); // 视频大小
let loading = ref();
let setUpList = ref(['内容编辑', '发布位置']);
let stepValue = ref(1); // 步骤调数值
let postionData = ref([]); // 缓存位置信息参数
let informationData = ref([]); // 缓存发布数据信息参数
onMounted(() => {
  console.log('这-进入页面', route.query);
  if (localStorage.getItem('postionData')) {
    postionData.value = JSON.parse(localStorage.getItem('postionData'));
    console.log('缓存位置信息参数', postionData.value);
  }
  if (localStorage.getItem('informationData')) {
    informationData.value = JSON.parse(localStorage.getItem('informationData'));
    console.log('缓存发布数据信息参数', informationData.value);
  }
  if (localStorage.getItem('informationData') && !route.query.id) {
    // let informationData = JSON.parse(localStorage.getItem('informationData'));
    // getEditDataShow({
    //   imageVideoVOList: informationData.infoBO.imageVideoBOList,
    //   infoVO: informationData.infoBO
    // });
  }

  if (route.query.state === 'device') {
    pattern.value = route.query.patternState;
    console.log('先设备后内容的设备信息', JSON.parse(localStorage.getItem('postionData')));
    positionTypes.value = JSON.parse(localStorage.getItem('postionData'))[0].positionType; // 应用平台 ==2
    setUpList.value = ['发布位置', '内容编辑'];
    stepValue.value = 2;
  }
  // 返回修改反显
  // if (route.query.returnData) {
  //   getReturnData(JSON.parse(route.query.returnData));
  // }
  // 通过route.query.id判断是新建发布还是修改发布
  if (route.query.id) {
    editData();
  }
});

// 转换时间戳
function getTimeFormat(timeS) {
  let time = new Date(timeS).getTime(); // 除1000 是变成秒级的时间戳 不除就是毫秒级
  return time;
}
function getReturnData(data) {
  compaPictureLists.value = data.infoBO.fileUrl;
  oldPositionBOList.value = data?.oldPositionBOList; // 位置信息
  console.log('数据', oldPositionBOList.value);
  getEditDataShow({
    imageVideoVOList: data.infoBO.imageVideoBOList,
    infoVO: data.infoBO
  });
}
// 删除图像相关
const deleteDialog = reactive({
  title: '温馨提示',
  content: '是否清空所有已上传图像 ？',
  warring: 'warring',
  visible: false,
  width: '330px'
});
// 弹窗相关
// 发布设置
const publishDialog = reactive({
  title: '发布设置',
  default: 'default',
  visible: false,
  butStatus: '确认发布',
  width: '545px'
});
const dialog = reactive({
  title: '文件上传',
  default: 'default',
  visible: false,
  width: '766px'
});
// 查看图像弹窗
const imgDialog = reactive({
  title: '图像预览',
  default: 'default',
  visible: false,
  width: '400px'
});
// 发布提示弹窗
const publishTipsDialog = reactive({
  title: '发布提示',
  default: 'default',
  visible: false,
  determineBtn: true,
  btnState: '继续发布',
  btnTitle: '返回修改',
  width: '832px'
});
const ruleList = reactive([
  {
    name: '正在发布信息',
    state: false
  },
  {
    name: '本次发布信息',
    state: true
  },
  {
    name: '正在发布信息',
    state: false
  }
]);
let conflictData = ref([]); // 冲突设备数据
// 冲突弹唱取消
function choiceEquipment(index, id) {
  conflictDevice.value.splice(index, 1);
  let data = [];
  postionData.value.forEach(item => {
    if (item.positionId !== id) {
      data.push({
        positionType: item.positionType,
        equipmentTypeName: item.equipmentTypeName,
        equipmentTypeId: item.equipmentTypeId,
        name: item.name,
        positionId: item.positionId,
        funcModule: item.funcModule,
        funcModuleName: item.funcModuleName
      });
    }
  });
  conflictData.value = conflictData.value.filter(items => {
    return items.positionId !== id;
  });
  if (conflictData.value.length === 0) {
    publishTipsDialog.determineBtn = false;
  } else {
    publishTipsDialog.determineBtn = true;
  }
}
// 发布提示确定
function publishTipsDialogOk() {
  publishTipsDialog.visible = false;
  params.positionBOList = conflictData.value;
  params.infoBO.pattern = pattern.value;
  console.log(444, params);
  saveInfoImage(params).then(res => {
    if (res.data.code === 200) {
      Message.success('发布成功');
      goHome();
    }
  });
}
// 发布提示返回修改
function publishTipsDialogOther() {
  publishTipsDialog.visible = false;
  let data = JSON.stringify(conflictData.value);
  localStorage.setItem('informationData', JSON.stringify(params));
  localStorage.setItem('postionData', data);
  router.push({
    path: '/position',
    query: {
      class: '图像',
      state: '设备',
      type: 'returnModify',
      pattern: route.query.patternState
    }
  });
}
const emit = defineEmits(['getShopCode']);
const imgDialogUrl = ref(''); // 弹窗图像地址
const fileList = ref([]); // 图像文件
const timeButton = ref('0'); // 时分秒
const coverFileList = ref([]); // 组图
const releasenameNumber = ref(0); // 发布名字数量
const describenameNumber = ref(0); // 描述数量
const releaseName = ref(''); // 发布名称
const durationTime = ref(5); // 展示时间
const describeName = ref(''); // 描述内容
const textData = ref('');
const titleValue = ref(''); // 内容标题
const compaPictureLists = ref([]); // 比较图像
const compareReleaseName = ref(''); // 比较名称
const compareDescribeName = ref(''); // 比较描述
const compareDurationTime = ref(''); // 比较时长
let pattern = ref(0); // 霸屏值
let params = reactive({
  infoBO: {
    pattern: 0, // ( 0普通模式 1霸屏模式)
    infoDesc: '',
    infoDuration: '',
    infoName: '',
    infoTimeType: '',
    infoType: 1, //  1图像 2文档 3文章
    // infoState: 0, // 发布信息状态 0发布中 1待生效 2已撤回 3已结束
    isDraft: 0, // 0非草稿 1草稿
    thumbnailUrl: '', // 封面
    validPeriodStart: '',
    validPeriodStop: '',
    isForever: 0, // 0非永久 1永久
    releaseOpportunityType: null, // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
    imageVideoBOList: [{ fileUrl: '' }] // 组图地址
  }
});
// 上传图像
let goBackState = ref([]); // 返回按钮状态是否弹弹窗
watch(pictureLists, (newName, oldName) => {
  // console.log(newName);
  // console.log(compaPictureLists.value);
  if (route.query.id) {
    if (newName === compaPictureLists.value) {
      emit('getShopCode', []);
      goBackState.value = [];
    } else {
      emit('getShopCode', '有改动');
      goBackState.value = '有改动';
    }
  } else {
    if (newName.length > 0) {
      emit('getShopCode', newName);
      goBackState.value = newName;
    } else {
      emit('getShopCode', []);
      goBackState.value = [];
    }
  }
});
// 发布名称
watch(releaseName, (newName, oldName) => {
  if (route.query.id) {
    if (newName === compareReleaseName.value) {
      emit('getShopCode', '');
      goBackState.value = '';
    } else {
      emit('getShopCode', newName);
      goBackState.value = newName;
    }
  } else {
    if (newName.length > 0) {
      emit('getShopCode', newName);
      goBackState.value = newName;
    } else {
      emit('getShopCode', '');
      goBackState.value = '';
    }
  }
});
// 发布描述
watch(describeName, (newName, oldName) => {
  if (route.query.id) {
    if (newName === compareDescribeName.value) {
      emit('getShopCode', '');
      goBackState.value = '';
    } else {
      emit('getShopCode', newName);
      goBackState.value = newName;
    }
  } else {
    if (newName.length > 0) {
      emit('getShopCode', newName);
      goBackState.value = newName;
    } else {
      emit('getShopCode', '');
      goBackState.value = '';
    }
  }
});
// 发布时长
watch(durationTime, (newName, oldName) => {
  if (route.query.id) {
    if (newName === compareDurationTime.value) {
      emit('getShopCode', '');
      goBackState.value = '';
    } else {
      emit('getShopCode', newName);
      goBackState.value = newName;
    }
  } else {
    if (newName !== compareDurationTime.value) {
      emit('getShopCode', newName);
      goBackState.value = newName;
    } else {
      emit('getShopCode', '');
      goBackState.value = '';
    }
  }
});
function minuteBtn() {
  timeButton.value = '1';
  if (durationTime.value > 1440) {
    durationTime.value = 1440;
  }
}
function hourBtn() {
  timeButton.value = '2';
  if (durationTime.value > 24) {
    durationTime.value = 24;
  }
}
// 删除图像弹窗取消
function deleteDialogCancel() {
  deleteDialog.visible = false;
}
// 删除图像确认事件
function deleteDialogOk() {
  deleteDialog.visible = false;
  progressValue.value = -1;
  if (!route.query.id) {
    let Objects = [];
    pictureLists.value.forEach(items => {
      Objects.push({
        Key: items.urlTime
      });
    });
    let id;
    let key;
    getAccessGet().then(res => {
      // console.log(555, res.data);
      id = res.data.data.Accesskeyid;
      key = res.data.data.Signature;
      deleteAllOBS(Objects, id, key);
    });
  }
  mergeLength.value = [];
  allSize.value = [];
  getSize(allSize.value);
  coverFileList.value = [];
  pictureLists.value = [];
}
// 清空
function empty() {
  deleteDialog.visible = true;
}
let publishTime = ref([dayjs(moment().format('YYYY-MM-DD HH:mm')), '']); // 发布设置弹窗时间
let permanentChecked = ref(false); // 永久发布switch状态
let publishStartDate = ref(''); // 发布设置弹窗开始时间
let publishEndDate = ref(''); // 发布设置弹窗结束时间
// 发布设置取消按钮
function publishDialogCancel() {
  publishDialog.visible = false;
  permanentChecked.value = false;
  publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
}
// 发布设置发布按钮
function publishDialogOk() {
  if (permanentChecked.value === false && publishEndDate.value === '') {
    Message.error('时长不能为空');
    return;
  }
  let equipmentIdList = []; // 设备id 集合
  postionData.value.forEach(item => {
    equipmentIdList.push(item.positionId);
  });
  // 发布设备冲突参数
  let releaseParamss = {
    current: 1,
    size: 10,
    data: {
      pattern: pattern.value,
      infoType: 1, // 1图像（视频+组图）   2文档  3文章
      validPeriodStart: moment().format('YYYY-MM-DD HH:mm:ss'),
      validPeriodStop:
        publishEndDate.value.length === 16 ? publishEndDate.value + ':00' : publishEndDate.value,
      equipmentIdList: equipmentIdList, // 暂时设备只能单选
      opportunityType: 0,
      isForever: permanentChecked.value ? 1 : 0
    }
  };
  if (permanentChecked.value) {
    releaseParamss.data.validPeriodStop = '9999-12-31 23:59:59';
    params.infoBO.validPeriodStop = '9999-12-31 23:59:59';
  } else {
    params.infoBO.validPeriodStop =
      publishEndDate.value.length === 16 ? publishEndDate.value + ':00' : publishEndDate.value;
  }
  // 发布参数
  let urlList = getUrlList(); // 获取图像数据(后台参数形式)
  params.infoBO.imageVideoBOList = urlList;
  params.infoBO.validPeriodStart = moment().format('YYYY-MM-DD HH:mm:ss');
  params.infoBO.isForever = permanentChecked.value ? 1 : 0;
  params.positionBOList = postionData.value;
  conflictData.value = postionData.value;
  params.infoBO.infoName = releaseName.value;
  params.infoBO.infoDesc = describeName.value;
  params.infoBO.infoTimeType = timeButton.value;
  params.infoBO.pattern = pattern.value;
  params.infoBO.infoDuration = durationTime.value;
  params.infoBO.releaseOpportunityType = 0; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
  let { type, fileUrl, coverUrl } = urlList[0];
  params.infoBO.thumbnailUrl = type === 1 ? coverUrl : fileUrl;
  if (positionTypes.value === 2) {
    saveInfoImage(params).then(res => {
      if (res.data.code === 200) {
        Message.success('发布成功');
        goHome();
      }
    });
  } else {
    getCheckCollideApi(releaseParamss);
  }
  publishDialog.visible = false;
  permanentChecked.value = false;
  publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
}
function disabledDate(current) {
  //  禁用当前时间之前的时间
  return current && current < moment().subtract(1, 'days').endOf('day');
}
// 当日只能选择当前时间之后的时间点
const range = (start, end) => {
  const result = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
};
const newS = ref('');
const currentTimes = ref('');
// 禁止当前时间之前的时间不可选
const disabledDateTime = (dates, partial) => {
  if (dates != null) {
    newS.value = moment(dates.$d).format('YYYY-MM-DD'); // 选择的时间
    currentTimes.value = moment(dates.$d).format('YYYY-MM-DD HH'); // 选择的时间
  }
  let currentTime = moment().format('YYYY-MM-DD'); // 当前时间
  let hours = moment().hours(); // 0~23
  let minutes = moment().minutes(); // 0~59
  let seconds = moment().seconds(); // 0~59
  if ((dates === null && partial === 'end') || newS.value === currentTime) {
    return {
      disabledHours: () => range(0, hours - 1),
      disabledMinutes: () => (currentTimes.value.slice(-2) <= hours ? range(0, minutes) : null),
      disabledSeconds: () => range(0, seconds - 1)
    };
  }
};

// 时间确认事件
function ok(date) {
  timeFn.value = timeFns(date[0], date[1]);
  let newS = moment(publishTime.value[1].$d).format('YYYY-MM-DD HH:mm'); // 选择的时间
  let currentDate = moment().format('YYYY-MM-DD HH:mm');
  if (newS <= currentDate) {
    Message.error('结束时间不能小于等于开始时间,请重新选择结束时间');
    publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), null];
    publishEndDate.value = '';
    timeFn.value = '0天0时0秒';
  }
}
// 时间取消事件
function onCalendarChange() {
  timeFn.value = '0天0时0秒';
}
let timeFn = ref('0天0时0秒');
// 时间框事件
function openChange(e) {
  if (e) {
    publishTime.value = [
      dayjs(moment().format('YYYY-MM-DD HH:mm')),
      dayjs(moment().format('YYYY-MM-DD HH:mm'))
    ];
    publishStartDate.value = moment().format('YYYY-MM-DD HH:mm');
  } else {
    if (publishEndDate.value === '') {
      publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
    } else {
      publishTime.value = [
        dayjs(moment().format('YYYY-MM-DD HH:mm')),
        dayjs(publishEndDate.value, 'YYYY-MM-DD HH:mm')
      ];
    }
  }
  if (publishEndDate.value !== '') {
    timeFn.value = timeFns(
      getTimeFormat(publishStartDate.value),
      getTimeFormat(publishEndDate.value)
    );
  }
}
function selsectTime(date, dateString) {
  publishStartDate.value = dateString[0];
  publishEndDate.value = dateString[1];
  disabledDateTime();
}

// 永久change
function isForeverChange() {
  if (permanentChecked.value) {
    publishTime.value = [
      dayjs(moment().format('YYYY-MM-DD HH:mm')),
      dayjs('9999-12-31 23:59', 'YYYY-MM-DD HH:mm')
    ];
  } else {
    publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
    timeFn.value = '0天0时0秒';
  }
  publishEndDate.value = '';
}
let thumbnailUrl = ref(''); // 封面地址
// 定时发布状态
let regularRelease = ref({
  visible: false
});
// 定时发布取消按钮
function regularReleaseCancel() {
  regularRelease.value.visible = false;
}
let huaWeiYunUrl = ref('https://saas-information.obs.cn-east-3.myhuaweicloud.com/'); // 华为云前缀
// 获取图像数据(后台参数形式)
function getUrlList() {
  let urlList = [];
  console.log(pictureLists.value);
  pictureLists.value.forEach(item => {
    urlList.push({
      coverUrl:
        item.coverUrl || 'https://saas-information.obs.cn-east-3.myhuaweicloud.com/' + item.urlTime, // 视频封面 现在没用了
      fileSize: item.sizes,
      fileUrl: huaWeiYunUrl.value + item.urlTime,
      type: item.urlTime.substr(item.urlTime.length - 1, 1) === '4' ? 1 : 0 // 0 图片 1 视频
    });
  });
  return urlList;
}
let conflictDevice = ref([]); // 冲突设备list
// 定时发布
function regularReleaseOk(data) {
  console.log('啊是多久啊是', data);
  if (data.isForever === false) {
    if (data.validPeriodStart === '' || data.validPeriodStop === '') {
      Message.warning('请选择有效期限');
      return;
    }
    if (data.releaseFrequency === 0) {
      if (data.daySiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    } else {
      if (data.weekSiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    }
  } else {
    if (data.releaseFrequency === 0) {
      if (data.daySiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    } else {
      if (data.weekSiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    }
  }
  let urlList = getUrlList(); // 获取图像数据(后台参数形式)
  let equipmentIdList = []; // 设备id 集合
  postionData.value.forEach(item => {
    equipmentIdList.push(item.positionId);
  });
  // 定时发布设备冲突参数
  let timeParams = {
    current: 1,
    size: 10,
    data: {
      pattern: pattern.value,
      infoType: 1, // 1图像（视频+组图）   2文档  3文章
      validPeriodStart: data.validPeriodStart,
      validPeriodStop: data.validPeriodStop,
      equipmentIdList: equipmentIdList,
      opportunityType: 1,
      isForever: permanentChecked.value ? 1 : 0,
      frequency: data.releaseFrequency, // 频率 0 天 1 周
      byWeekList: data.releaseFrequency === 1 ? data.weekSiteBOList : [], // 周
      byDayList: data.releaseFrequency === 0 ? data.daySiteBOList : [] // 天
    }
  };
  params.infoBO.imageVideoBOList = urlList;
  params.positionBOList = postionData.value;
  conflictData.value = postionData.value;
  params.infoBO.validPeriodStart = data.validPeriodStart; // 有效期开始
  params.infoBO.validPeriodStop = data.validPeriodStop; // 有效期结束
  params.infoBO.isForever = data.isForever ? 1 : 0; // 0非永久 1永久
  params.infoBO.releaseOpportunityType = data.releaseFrequency === 0 ? 1 : 2; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
  params.infoBO.releaseFrequency = data.releaseFrequency; // 发布频率 0每天 1每周
  params.infoBO.infoName = releaseName.value;
  params.infoBO.infoDesc = describeName.value;
  params.infoBO.infoTimeType = timeButton.value;
  params.infoBO.infoDuration = durationTime.value;
  params.infoBO.thumbnailUrl = urlList[0].coverUrl;
  if (data.releaseFrequency === 0) {
    params.infoBO.daySiteBOList = data.daySiteBOList; // 按天发布 数组
  } else {
    params.infoBO.weekSiteBOList = data.weekSiteBOList; // 按周的定时发布 数组
  }
  // console.log(444, params.infoBO);
  params.infoBO.pattern = pattern.value;
  // console.log(444, params);
  regularRelease.value.visible = false;
  getCheckCollideApi(timeParams);
}
// 设备冲突接口
function getCheckCollideApi(timeParams) {
  checkCollide(timeParams).then(res => {
    // 未返回数据 代表没有冲突设备
    if (res.data.data.records.length === 0) {
      saveInfoImage(params).then(res => {
        if (res.data.code === 200) {
          Message.success('发布成功');
          goHome();
        }
      });
    } else {
      // 打开设备冲突 弹窗
      conflictDevice.value = res.data.data.records;
      publishTipsDialog.visible = true;
    }
  });
}
let oldPositionBOList = ref([]); // 位置信息
let isForever = ref(); // 永久状态
let releaseOpportunityType = ref(); //
let validPeriodStart = ref();
let validPeriodStop = ref();
let weekSiteVOList = ref([]); // 定时发布时间/周
let daySiteVOList = ref([]); // 定时发布时间/天
// 编辑时赋值
function editData() {
  getInfoImage(route.query.id).then(res => {
    let data = res.data.data;
    oldPositionBOList.value = data?.positionVOList; // 位置信息
    console.log('数据', oldPositionBOList.value);
    getEditDataShow(data); // 展示图像页面数控
  });
}
// 展示图像页面数据
function getEditDataShow(data) {
  console.log(data, 77777);
  let size = [];
  let photoData = [];
  data.imageVideoVOList.forEach(item => {
    let type =
      item.fileUrl.substr(item.fileUrl.length - 1, 1) === 'g' ||
      item.fileUrl.substr(item.fileUrl.length - 1, 1) === 'G'
        ? 'img'
        : 'video';
    photoData.push({
      status: 'done',
      progressValue: 100, // 反显数据按100处理
      thumbUrl: getEscapeUrl(item.fileUrl, 'url'),
      exception: 'exceptionSuccess',
      sizes: item.fileSize * 1,
      urlTime: getEscapeUrl(item.fileUrl, 'assetsUrl'),
      name: getEscapeUrl(item.fileUrl, 'name'),
      customType: type,
      url: getEscapeUrl(item.fileUrl, 'url'),
      coverUrl: item.coverUrl
    });
    customType.value.push(type);
    size.push({
      size: item.fileSize * 1,
      urlTime: item.fileUrl
    });
    allSize.value = size;
    getSize(allSize.value);
  });
  console.log(photoData);
  compareReleaseName.value = data.infoVO.infoName;
  compareDescribeName.value = data.infoVO.infoDesc;
  compareDurationTime.value = data.infoVO.infoDuration;
  pictureLists.value = photoData;
  coverFileList.value = JSON.parse(JSON.stringify(photoData));
  compaPictureLists.value = photoData;
  releaseName.value = data.infoVO.infoName;
  describeName.value = data.infoVO.infoDesc;
  durationTime.value = data.infoVO.infoDuration;
  timeButton.value = String(data.infoVO.infoTimeType);
  describenameNumber.value = describeName.value?.length;
  releasenameNumber.value = releaseName.value?.length;
  releaseOpportunityType.value = data.infoVO.releaseOpportunityType;
  validPeriodStart.value = data.infoVO.validPeriodStart;
  validPeriodStop.value = data.infoVO.validPeriodStop;
  isForever.value = data.infoVO.isForever;
  weekSiteVOList.value = data.weekSiteVOList; // 发布时间/周
  daySiteVOList.value = data.daySiteVOList; // 发布时间/天
  createTime.value = data.infoVO.createTime; // 创建时间allSizeNum
  pattern.value = data.infoVO.pattern;
  params.infoBO.pattern = data.infoVO.pattern;
}
// 删除图像
function deleteImg(index) {
  if (!route.query.id) {
    deleteOBS(pictureLists.value[index].urlTime);
  }
  let data = [];
  allSize.value.splice(index, 1);
  pictureLists.value.splice(index, 1);
  coverFileList.value.splice(index, 1);
  pictureLists.value.forEach(item => {
    data.push(item.customType);
  });
  customType.value = data;
  getSize(allSize.value);
}
let tipType = ref(''); // 弹窗预览视频类型
// 查看图像
function lookImg(index) {
  imgDialog.visible = true;
  tipType.value = pictureLists.value[index].customType;
  imgDialogUrl.value =
    pictureLists.value[index].lastModified !== undefined
      ? huaWeiYunUrl.value + pictureLists.value[index].urlTime
      : pictureLists.value[index].url;
  console.log('imgDialogUrl.value', imgDialogUrl.value);
  previewImgs.value = pictureLists.value.map(item => item.url);
  curImgIdx.value = index;
  console.log('previewImgs.value', previewImgs.value);
  console.log('curImgIdx.value', curImgIdx.value);
}
function imgDialogCancel() {
  imgDialog.visible = false;
}
// 发布内容
function releaseNameChange(value) {
  if (value.length > 50) {
    releaseName.value = value.substring(0, 50);
    releasenameNumber.value = 50;
  } else {
    releasenameNumber.value = value.length;
  }
}
// 描述内容
function describeNameChange(value) {
  if (value.length > 140) {
    describeName.value = value.substring(0, 140);
    describenameNumber.value = 140;
  } else {
    describenameNumber.value = value.length;
  }
}
let removeState = ref(true);
// 移除组图
function deletePhoto(urlTime, index) {
  // uploadEndList
  if (!route.query.id) {
    deleteOBS(urlTime);
    coverFileList.value.forEach((item, index) => {
      if (item.urlTime === urlTime) {
        coverFileList.value.splice(index, 1);
        allSize.value.splice(index, 1);
        uploadEndList.value.splice(index, 1);
        getSize(allSize.value);
      }
    });
    pictureLists.value.forEach((item, index) => {
      if (item.urlTime === urlTime) {
        pictureLists.value.splice(index, 1);
      }
    });
  } else {
    pictureLists.value.forEach((item, index) => {
      if (item.urlTime === urlTime) {
        pictureLists.value.splice(index, 1);
        allSize.value.splice(index, 1);
        uploadEndList.value.splice(index, 1);
        getSize(allSize.value);
      }
    });
  }
  removeState.value = false;
}
// 处理重新发布数据
function getAgainFile(urlTime) {
  console.log('重新上传数据', againData.value);
  console.log(urlTime);
  againData.value.forEach((item, index) => {
    if (item.file.urlTime === urlTime) {
      handleChange(item);
    }
  });
}
// 图像上传
let againData = ref([]); // 重新上传数据
async function handleChange(file, fileList) {
  let sizes = [];
  for (const key in coverFileList.value) {
    if (
      coverFileList.value[key].originFileObj?.progressValue === 100 ||
      coverFileList.value[key].originFileObj?.progressValue === undefined
    ) {
      sizes.push(coverFileList.value[key].size * 1);
    }
  }
  let fileName = file.file.name;
  let index = file.file.name.lastIndexOf('.');
  let name = fileName.substring(0, fileName.lastIndexOf('.'));
  let lastName = '.' + fileName.substring(index + 1);
  if ((allSizeNum.value + file.file.size * 1) / 1024 / 1024 / 1024 >= 5) {
    progressValue.value = -1;
    file.file['status'] = 'error';
    file.file['response'] = '文件超出上传限制!';
    Message.error('文件超出上传限制!');
    file.pop();
  } else if (file.size / 1024 / 1024 > 5) {
    progressValue.value = -1;
    file.file['status'] = 'error';
    file.file['response'] = '文件超出上传限制!';
    Message.error('文件超出上传限制!');
    file.pop();
  } else if (name.length > 50) {
    progressValue.value = -1;
    file.file['status'] = 'error';
    file.file['response'] = '图像名超出字符限制，请修改后重新上传!';
    Message.error('图像名超出字符限制，请修改后重新上传!');
  } else if (
    lastName.toLowerCase() !== '.png' &&
    lastName.toLowerCase() !== '.jpg' &&
    lastName.toLowerCase() !== '.jpeg' &&
    lastName.toLowerCase() !== '.mp4' &&
    lastName.toLowerCase() !== '.avi'
  ) {
    progressValue.value = -1;
    file.file['status'] = 'error';
    file.file['response'] = '只支持.png .jpg .jpeg .mp4格式!';
    Message.error('只支持.png .jpg .jpeg .mp4格式');
  } else if (file.file.size === 0) {
    file.file['status'] = 'error';
    progressValue.value = -1;
    file.file['response'] = '文件大小不能为0KB!';
    Message.error('文件大小不能为0KB!');
  } else {
    if (file.file.type === 'image/jpeg' || file.file.type === 'image/png') {
      file.file['customType'] = 'img';
    } else {
      // 截取视频第一帧并赋值
      let { url, typrUrl } = await captureImage(file);
      await getCoverFile(url, typrUrl);
      file.file['coverUrl'] = `https://saas-information.obs.cn-east-3.myhuaweicloud.com/${typrUrl}`;

      file.file['customType'] = 'video';
    }
    progressValue.value = 0;
    file.file['filetype'] = lastName; // 类型 .png
    file.file['filename'] = name; // 单独名字
    file.file['time'] = file.file['time'] ? file.file['time'] : new Date().getTime();
    // console.log(9999, process.env);
    let urlTime =
      process.env.VUE_APP_WEB_URL_OBSBUCKET +
      '/assets/' +
      moment().format('YYYY-MM-DD') +
      '/' +
      file.file['time'] +
      '_tupian' +
      file.file.filetype;
    file.file['urlTime'] = urlTime;
    file.file['status'] = 'done';
    file.file['sizes'] = file.file.size; // kb大小
    file.file['sizesKb'] = file.file.size; // kb大小
    // file.file['uploadState'] = 'start';
    file.file['retry'] = 'retrys';
    // file.file['exception'] = 'exceptionSuccess'; // 上传状态
    allSizeNum.value = getSum(sizes) + file.file.size;
    allSize.value.push({ size: file.file.size * 1, urlTime: file.file.urlTime });
    getSize(allSize.value);
    // console.log(111, file);
    uploadObs(file);
  }
}
let uploadEndList = ref([]);
let photoList = ref([]);
let uploadStateList = ref([]); // 上传图像状态集合 uploadState
let progressValue = ref(-1); // 上传进度数值
let customType = ref([]); // 图像类型集合
let allSize = ref([]); // 图像总大小集合
let allSizeNum = ref(0); // 图像总大小
// 上传华为云
function uploadObs(file) {
  // console.log(coverFileList.value);
  if (
    // 视频格式
    file.file.type === 'video/mp4' ||
    file.file.type === 'video/avi'
  ) {
    file.file.thumbUrl =
      'https://saas-information.obs.cn-east-3.myhuaweicloud.com/assets/img/appendix_icon_mp4.png';
  }
  let id;
  let key;
  getAccessGet().then(res => {
    // console.log(555, res.data);
    id = res.data.data.Accesskeyid;
    key = res.data.data.Signature;
  });
  let fileDir = file.file.urlTime;
  let SourceFile = file.file;
  let obsClient = new ObsClient({
    access_key_id: id,
    secret_access_key: key,
    server: 'https://obs.cn-east-3.myhuaweicloud.com'
  });
  obsClient.putObject(
    {
      Bucket: 'saas-information',
      Key: fileDir,
      SourceFile: SourceFile, // 文件encodeURIComponent
      ProgressCallback: function (transferredAmount, totalAmount, totalSeconds) {
        // transferredAmount, totalAmount, totalSeconds 已上传的字节数、总字节数、已使用的时间
        file.file['progressValue'] = Number(((transferredAmount / totalAmount) * 100).toFixed(2));
        // file.file['exception'] = 'exceptionLoading'; // 上传成功（exceptionSuccess） 上传失败（exceptionError） 上传中（exceptionLoading）
        getProgressLine('exceptionLoading'); // 单纯获取进度条（共用getUploadData方法，失败情况exception值响应式 改变不过来）
      }
    },
    function (err, result) {
      if (err) {
        file.file['retry'] = 'retry'; // 重新上传（上传失败存在）
        againData.value.push(file.file.uploadState !== 100 ? file : null);
        let size = [];
        pictureLists.value.forEach(item => {
          size.push({
            size: item.sizes * 1,
            urlTime: item.urlTime
          });
        });
        allSize.value = size;
        getSize(allSize.value);
        getProgressLine('exceptionError');
        Message.error('上传失败');
      } else {
        // file.file['uploadState'] = 'success';
        getProgressLine('exceptionSuccess');
      }
    }
  );
}
let allSchedule = ref(true); // 所有上传进度(全是100 true, false)
function getProgressLine(type, again) {
  // type=>三个状态 上传中 上传成功 上传失败
  let list = [];
  coverFileList.value.forEach(item => {
    if (item?.originFileObj) {
      if (item.originFileObj.status !== 'error') {
        // console.log(item.originFileObj.progressValue);
        let name;
        name = huaWeiYunUrl.value + item.originFileObj.urlTime;
        list.push({
          // newUpload: 'newUpload', // 是否是新的上传 还是已经上传的（newUpload新的上传；oldUpload上次上传或者默认回显）暂时用不上
          progressValue:
            item.originFileObj?.retry === 'retry' ? 50 : item.originFileObj.progressValue, // 上传进度（0.1,...99，100）
          // exception: item.originFileObj.progressValue === 100 ? 'exceptionSuccess' : type, // 上传成功还是上传失败, 上传中（exceptionError，exceptionSuccess，exceptionLoading）
          exception: getUploadType(item, type), // 上传成功还是上传失败, 上传中（exceptionError，exceptionSuccess，exceptionLoading）
          // again:again, // 重新上传（shangc）
          url: name,
          thumbUrl: name, // 封面
          customType: item.originFileObj.customType, // img / video
          urlTime: item.originFileObj.urlTime, // assets/2023-10-07/1696657673277_23.7M.jpg
          sizes: item.originFileObj.sizes, // 大小 (kb)
          coverUrl: item.originFileObj.coverUrl // 视频第一帧图片
        });
      }
    } else {
      list.push({
        exception: 'exceptionSuccess',
        progressValue: 100,
        url: item.url,
        thumbUrl: item.thumbUrl, // 封面
        customType: item.customType, // img / video
        urlTime: item.urlTime, // assets/2023-10-07/1696657673277_23.7M.jpg
        sizes: item.sizes, // 大小 (kb)
        coverUrl: item.coverUrl // 视频第一帧图片
      });
    }
  });
  setTimeout(() => {
    // pictureLists.value = arrayUnique(pictureLists.value.concat(list), 'urlTime'); // 数组去重保留最后一个进度
    pictureLists.value = arrayUnique(list, 'urlTime'); // 数组去重保留最后一个进度
    allSchedule.value = getAllSchedule(pictureLists.value); // 所有上传进度(全是100 true, false)
    // console.log('上传全部list', pictureLists.value);
  }, 200);
}
function getUploadType(item, type) {
  if (item.originFileObj?.retry === 'retry') {
    return 'retry';
  } else if (item.originFileObj.progressValue === 100) {
    return 'exceptionSuccess';
  } else {
    return type;
  }
}
// 获取当前上传得所有进度
function getAllSchedule(data) {
  let list = [];
  data.forEach(item => {
    list.push(item.progressValue);
  });
  // console.log(list);
  if (list.every(num => num === 100)) {
    // console.log('数组中都是100的值');
    return true;
  } else {
    // 打开另一个提示弹窗
    // console.log('数组中存在不是100的值');
    return false;
  }
}
function getSize(data) {
  let value = [];
  if (data) {
    data.forEach(item => {
      value.push(item.size);
    });
    allSizeNum.value = getSum(value);
  } else {
    allSizeNum.value = 0;
  }
  // console.log('大小', allSizeNum.value);
}
let mergeLength = ref([]);
let createTime = ref(''); // 返回的创建时间
const activeKey = ref('1');
const timingData = ref({});
let regularReleaseChild = ref(null);
const timingState = ref('');
// 共享事件
function onPublic(value) {
  console.log(444, pictureLists.value);
  console.log(444, route.query.state);
  console.log(allSchedule.value);
  let errorList = []; // 失败图像数组
  pictureLists.value.forEach(item => {
    if (item.exception === 'exceptionError') {
      errorList.push(item.exception);
    }
  });
  if (errorList.length !== 0) {
    Message.warning('部分视频或图片上传失败，请检查后继续操作');
    return;
  }
  if (!allSchedule.value) {
    Message.warning('图像上传中请勿操作');
    return;
  }
  let urlList = getUrlList(); // 获取图像数据(后台参数形式)
  if (pictureLists.value.length <= 0) {
    Message.warning('请上传图像');
    return;
  }
  if (releaseName.value.replace(/\s+/g, '') === '') {
    Message.warning('发布名称不能为空');
    return;
  }
  // cutImage();
  setTimeout(() => {
    console.log('pictureLists.value', pictureLists.value);
    toData(value);
  }, 500);
}
function toData(value) {
  let urlList = [];

  pictureLists.value.forEach(item => {
    urlList.push({
      coverUrl:
        item.coverUrl || 'https://saas-information.obs.cn-east-3.myhuaweicloud.com/' + item.urlTime,
      fileSize: item.sizes,
      fileUrl: `https://saas-information.obs.cn-east-3.myhuaweicloud.com/` + item.urlTime,
      type: item.urlTime.substr(item.urlTime.length - 1, 1) === '4' ? 1 : 0 // 0 图片 1 视频
    });
  });

  publishTipsDialog.determineBtn = true;
  // conflictData.value = JSON.parse((route.query.positionBOList));
  if (value === 1) {
    // if (route.query.returnData) {
    //   let data = JSON.parse(route.query.returnData);
    //   if (data.infoBO.isForever === 1) {
    //     permanentChecked.value = true;
    //   } else {
    //     permanentChecked.value = false;
    //   }
    //   if (data.infoBO.releaseOpportunityType === 0) {
    //     //  普通发布0 定时发布1
    //     publishEndDate.value = data.infoBO.validPeriodStop;
    //     publishStartDate.value = data.infoBO.validPeriodStart;
    //     publishTime.value = [
    //       dayjs(data.infoBO.validPeriodStart.substring(0, 16), 'YYYY-MM-DD HH:mm'),
    //       dayjs(data.infoBO.validPeriodStop.substring(0, 16), 'YYYY-MM-DD HH:mm')
    //     ];
    //     // 时间差的毫秒数
    //     timeFn.value = timeFns(
    //       getTimeFormat(data.infoBO.validPeriodStart),
    //       getTimeFormat(data.infoBO.validPeriodStop)
    //     );
    //   } else {
    //     permanentChecked.value = false;
    //     publishEndDate.value = '';
    //     publishStartDate.value = '';
    //   }
    // }
    publishDialog.visible = true;
  } else if (value === 2) {
    // if (route.query.returnData) {
    //   let datas = JSON.parse(route.query.returnData);
    //   if (datas.infoBO.daySiteBOList) {
    //     datas.daySiteVOList = datas.infoBO.daySiteBOList;
    //   }
    //   timingData.value = datas;
    //   timingState.value = '1';
    //   regularReleaseChild.value.getDatas(timingData.value, '1');
    // }
    regularRelease.value.visible = true;
  } else if (value === 'to') {
    console.log('to-下一步，新建下一步 与编辑下一步');
    let urlList = getUrlList(); // 获取图像数据(后台参数形式)
    params.infoBO.imageVideoBOList = urlList;
    params.infoBO.infoName = releaseName.value.replace(/\s+/g, '');
    params.infoBO.infoDesc = describeName.value;
    params.infoBO.infoTimeType = timeButton.value;
    params.infoBO.infoDuration = durationTime.value;
    params.infoBO.thumbnailUrl =
      thumbnailUrl.value === '' ? urlList[0].coverUrl : thumbnailUrl.value;
    params.oldPositionBOList = oldPositionBOList.value;
    console.log(8888, route.query.state === '编辑');
    if (route.query.state === '编辑') {
      // 发布内容详情进行修改
      params.infoBO.id = route.query.id;
      params.infoBO.pattern = pattern.value;
      params.infoBO.isForever = isForever.value;
      params.infoBO.releaseOpportunityType = releaseOpportunityType.value; // releaseOpportunityType null 0 1 2
      params.infoBO.validPeriodStart = validPeriodStart.value; // 开始时间
      params.infoBO.validPeriodStop = validPeriodStop.value; // 结束时间
      params.infoBO.pushTime = createTime.value; // 创建时间
      params.weekSiteVOList = weekSiteVOList.value; // 发布时间-周
      params.daySiteVOList = daySiteVOList.value; // 发布时间-天
      let data = JSON.stringify(params);
      console.log(params);
      localStorage.setItem('postionData', data);
      localStorage.setItem('informationData', data);
      // store.commit("addCacheRoute", "postMessage");
      store.commit('addCacheRoute', 'postion');
      store.commit('addCacheRoute', 'postMessage');
      store.commit('addCacheRoute', 'imgAndVideo');
      router.push({
        path: '/position',
        query: {
          // data: data,
          state: '编辑',
          releaseType: 13
        }
      });
    } else {
      // 新建
      console.log(params, '发布信息数据-也就是文章，图像数据');
      let datas = JSON.stringify(params);
      localStorage.setItem('informationData', datas);
      localStorage.setItem('postionData', localStorage.getItem('postionData'));
      store.commit('addCacheRoute', 'postMessage');
      store.commit('addCacheRoute', 'imgAndVideo');
      store.commit('addCacheRoute', 'postion');
      router.push({
        path: '/position',
        query: {
          // data: data,
          // state: '编辑', // 暂时添加按照编辑逻辑
          id: route.query.state === '重新发布' ? route.query.id : null,
          state: route.query.state,
          type: '组图',
          releaseType: 13
        }
      });
    }
  } else {
    loading.value = true;
    if (value === 3) {
      params.positionBOList = postionData.value;
    }
    // cutImage();
    setTimeout(() => {
      console.log(urlList);
      params.infoBO.thumbnailUrl = urlList[0].coverUrl;
      params.infoBO.infoName = releaseName.value.replace(/\s+/g, '');
      params.infoBO.infoDesc = describeName.value;
      params.infoBO.infoTimeType = timeButton.value;
      params.infoBO.infoDuration = durationTime.value;
      params.infoBO.isDraft = 1;
      params.infoBO.imageVideoBOList = urlList;
      if (route.query.state === '草稿箱修改') {
        params.infoBO.id = route.query.id;
      }
      console.log('参数', params);
      saveInfoImageDraft(params).then(res => {
        if (res.data.code === 200) {
          loading.value = false;
          Message.success('保存草稿成功');
          goHome();
        }
      });
    }, 100);
  }
}
function goHome() {
  store.commit('removeCacheRoute', 'postion');
  store.commit('removeCacheRoute', 'postMessage');
  store.commit('removeCacheRoute', 'imgAndVideo');
  router.push({
    path: '/'
  });
}

// =====================================================================================
//   郭亚山
// =================================================================================
function cutImage() {
  pictureLists.value.forEach((video, index) => {
    if (video.customType === 'video') {
      const videos = document.getElementById(index);
      // console.log(videos);
      let canvas = document.createElement('canvas'); // 获取 canvas 对象
      const ctx = canvas.getContext('2d'); // 绘制2d
      videos.currentTime = 1; // 第一帧
      // video.oncanplay = () => {
      // console.log('video', videos);
      canvas.width = videos.clientWidth; // 获取视频宽度
      canvas.height = videos.clientHeight; // 获取视频高度
      // 利用canvas对象方法绘图
      ctx.drawImage(videos, 0, 0, videos.clientWidth, videos.clientHeight);
      // 转换成base64形式
      const url = canvas.toDataURL('image/png'); // 截取后的视频封面
      let typrUrl =
        'assets/' +
        moment().format('YYYY-MM-DD') +
        '/' +
        new Date().getTime() +
        '_' +
        index +
        'tupian.png';
      getCoverFile(url, typrUrl);
    }
  });
  // setTimeout(() => {
  allCoverList.value = quchong(allCoverList.value, 'name');
  // console.log(allCoverList.value);
  pictureLists.value.forEach((item, index) => {
    if (item.customType === 'video') {
      allCoverList.value.forEach(ite => {
        console.log(ite.name.substr(0, ite.name.length - 10) * 1);
        if (ite.name.substr(0, ite.name.length - 10) * 1 === index * 1) {
          item.coverUrl = ite.url;
        }
      });
    }
  });
  // console.log(111, pictureLists.value);
  // }, 1000);
}
function quchong(dataList, id) {
  let res = []; // 去重复后的集合
  let tem = {};
  for (let i = 0; i < dataList.length; i++) {
    if (!tem[dataList[i][id]]) {
      res.push(dataList[i]);
      tem[dataList[i][id]] = 1;
    }
  }
  return res;
}

async function getCoverFile(imgUrl, index) {
  // allCoverList.value.push({
  //   url: 'https://saas-information.obs.cn-east-3.myhuaweicloud.com/' + index,
  //   name: index.substring(index.lastIndexOf('_') + 1)
  // });
  // console.log('封面allCoverList.value', allCoverList.value);

  await getImageFileFromUrl(imgUrl, 'fileName', index)
    .then(response => {
      // 返回的是文件对象，使用变量接收即可
      // console.log(response);
      coverUploadObs(response, index);
    })
    .catch(e => {
      console.error(e);
    });
}
let allCoverList = ref([]); // 所有封面数组
function coverUploadObs(file, index) {
  let id;
  let key;
  getAccessGet().then(res => {
    // console.log(555, res.data);
    id = res.data.data.Accesskeyid;
    key = res.data.data.Signature;
  });
  let fileDir = file.urlTime;
  let SourceFile = file;
  let obsClient = new ObsClient({
    access_key_id: id,
    secret_access_key: key,
    server: 'https://obs.cn-east-3.myhuaweicloud.com'
  });
  obsClient.putObject(
    {
      Bucket: 'saas-information',
      Key: fileDir,
      SourceFile: SourceFile // 文件encodeURIComponent
    },
    function (err, result) {
      if (err) {
        console.log('上传失败');
      } else {
        console.log('上传成功', index);
      }
    }
  );
}
/**
 * 根据图片url转为png文件对象
 * @param url
 * @param imageName
 * @returns {Promise<unknown>}
 */
function getImageFileFromUrl(url, imageName, index) {
  return new Promise((resolve, reject) => {
    let blob = null;
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.setRequestHeader('Accept', 'image/png');
    xhr.responseType = 'blob';
    // 加载时处理
    xhr.onload = () => {
      // 获取返回结果
      blob = xhr.response;
      let imgFile = new File([blob], imageName, { type: 'image/png' });

      imgFile['urlTime'] = index;
      // console.log(imgFile);
      // 返回结果
      resolve(imgFile);
    };
    xhr.onerror = e => {
      reject(e);
    };
    // 发送
    xhr.send();
  });
}

// 视频截取第一帧
let coverIdx = 0;
const captureImage = (file, time = 1, coverWidth = 300) => {
  return new Promise((resolve, reject) => {
    const element = document.createElement('video');
    // 设置视频源以及视频加载时长
    Object.assign(element, {
      src: URL.createObjectURL(file.file),
      currentTime: time
    });
    // 添加监听事件：在指定的帧数据加载完成后
    element.addEventListener('loadeddata', function () {
      const { videoWidth, videoHeight } = this;
      // 创建画布
      const canvas = document.createElement('canvas');
      // 根据指定的封面宽度，等比例设置画布大小
      Object.assign(canvas, {
        width: videoWidth,
        height: videoHeight
      });
      canvas
        .getContext('2d')
        // 以视频元素作为图片源，从中抓取当前帧作为一个图像
        .drawImage(this, 0, 0, canvas.width, canvas.height);
      let url = canvas.toDataURL('image/png');
      let typrUrl =
        'assets/' +
        moment().format('YYYY-MM-DD') +
        '/' +
        new Date().getTime() +
        '_' +
        coverIdx +
        'tupian.png';
      coverIdx++;
      resolve({ url, typrUrl });
    });
  });
};
</script>
<style lang="less" scoped>
@import './index.less';
@import './header.less';
</style>
